import axios from "axios";
import store from "@/store";
import { Message } from "element-ui";
import router from "@/router";
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000, // request timeout
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    config.headers.Authorization = store.state.user.token || "";
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    if (response.data.code !== 10000) {
      Message.error(response.data.msg);
      return Promise.reject(response.data);
    } else {
      return response.data;
    }
  },
  (error) => {
    // 相应错误状态码 4xx-5xxx
    // 统一错误处理
    if (error.response.status === 401) {
      store.commit("user/removeToken");
      router.push("/login");
    }
    Message.error(error.response.data.msg);
    return Promise.reject(error);
  },
);

export default service;
